package com.kalvan.core.res;

import com.kalvan.core.exception.BizException;
import com.kalvan.core.exception.ReturnCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;

/**
 * 基础返回对象
 *
 * @author chenliang
 */
@Getter
@ApiModel(value = "返回对象")
public class Result<T> implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 4位返回码 0000表示请求处理成功,如果是交易具体交易状态需要再解析data的数据
     * 定义 extends ReturnCode
     * 返回码 xxxxReturnCode.code
     */
    @ApiModelProperty(value = "返回码", required = true)
    protected String code;

    /**
     * 返回描述 xxxxReturnCode.msg
     */
    @ApiModelProperty(value = "返回说明", required = true)
    protected String msg;

    /**
     * 返回明细数据
     */
    @ApiModelProperty(value = "返回数据,具体数据格式参照接口说明", required = true)
    protected T data;

    /**
     * @param code
     * @param msg
     * @return
     */
    public static Result buildResult(String code, String msg) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    /**
     * 根据返回码解析返回对象
     *
     * @param returnCode
     * @return
     */
    public static Result buildResult(ReturnCode returnCode) {
        Result result = new Result();
        result.setCode(returnCode.getCode());
        result.setMsg(returnCode.getMsg());
        return result;
    }

    /**
     * 根据biz异常解析返回对象
     *
     * @param exception
     * @return
     */
    public static Result buildResult(BizException exception) {
        Result result = new Result();
        result.setCode(exception.getCode());
        result.setMsg(exception.getMsg());
        return result;
    }

    public Result setCode(String code) {
        this.code = code;
        return this;
    }

    public Result setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public Result setData(T data) {
        this.data = data;
        return this;
    }
}
